using System.Xml;
using System.Collections.Generic;

namespace RealDolmen.SharePoint.ListFeatures.Elements
{
    public class ListFeatureEventsElement : ListFeatureElement, IListFeatureTrackerReferencee
    {
        List<ListFeatureEventElement> eventsElements;

        public static string RootTag
        {
            get { return "Receivers";  }
        }

        #region Overrides
        public override string FullKey
        {
            get { return null; }
        }
        public override string Key
        {
            get { return null; }
        }

        public override bool Customizable
        {
            get { return false; }
        } 
        #endregion // Overrides

        #region Activate / Deactivate
        public override void Activate(ListFeature listFeature)
        {
            ConstructEventElements();

            foreach (ListFeatureEventElement eventElement in eventsElements)
            {
                eventElement.Activate(listFeature);
            }

        }

        private void ConstructEventElements()
        {
            if (eventsElements == null)
            {
                eventsElements = new List<ListFeatureEventElement>();

                foreach (XmlNode node in XmlDefinition.ChildNodes)
                {
                    if (node.Name == ListFeatureEventElement.RootTag)
                    {
                        ListFeatureEventElement eventElement = new ListFeatureEventElement();
                        eventElement.ElementsFile = ElementsFile;
                        eventElement.XmlDefinition = node;
                        eventElement.FeatureDefinition = FeatureDefinition;
                        eventsElements.Add(eventElement);
                    }
                }
            }
        }

        public override void Deactivate(ListFeature listFeature)
        {

            if (ListFeature.GetActiveListFeatures(listFeature.ParentList, listFeature.Definition).Count < 2)
            {
                ConstructEventElements();

                foreach (ListFeatureEventElement eventElement in eventsElements)
                {
                    eventElement.Deactivate(listFeature);
                }
            }
        } 
        #endregion // Activate / Deactivate

        #region IListFeatureTrackerReferencee Members

        public void UpdateTrackerReference(ListFeature listFeature, string oldTrackerData)
        {
            ConstructEventElements();

            foreach (ListFeatureEventElement eventElement in eventsElements)
            {
                eventElement.UpdateTrackerReference(listFeature, oldTrackerData);
            }
        }

        #endregion
    }
}